<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :visible.sync="drawerShow"
    :size="showMobilePage ? '100%' : '80%'"
    title="选择发票"
    append-to-body
  >
    <div class="drawer-content">
      <filter-input
        ref="FilterToolRef"
        v-model="filterInput"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <el-tabs v-if="multiple" v-model="curTabName" type="card" class="tab-content" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="发票列表" name="all"/>
        <el-tab-pane name="selected">
          <span slot="label">已选择发票<el-badge v-if="selectedData.length" :value="selectedData.length" /></span>
        </el-tab-pane>
      </el-tabs>
      <div :style="multiple?'':{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <el-table
            v-if="(curTabName === 'all' && list.items.length > 0) || (curTabName === 'selected' && selectedData.length > 0)"
            ref="legalTableRef"
            :data="curTabName === 'all'?list.items:selectedTableData"
            :row-class-name="(data) => tableRowClassName(data)"
            :height="setTableHeight"
            class="fb-table"
            header-cell-class-name="order-data-header-cell"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            fit
            select-callback
            hightlight-current-rowref="tableRef"
            @sort-change="sortMethod"
            @select="selectTable"
            @select-all="selectTable">
            <el-table-column
              fixed="left"
              align="center"
              type="selection"
              width="50"
            />
            <!-- <el-table-column align="left" label="发票编号">
              <template slot-scope="scope">
                <span>{{ scope.row.no || '--' }}</span>
              </template>
            </el-table-column> -->
            <el-table-column align="left" label="发票号码" min-width="120">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.number" :open-delay="800">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.number }}</div>
                  <div class="ellipsisOne" style="color: #406eff; cursor: pointer;" @click="goInvoice(scope.row)">
                    {{ scope.row.number }}
                  </div>
                </el-tooltip>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="发票类型" min-width="130">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceType" />
                <!-- <span>{{ scope.row.invoiceType | invoiceTypeFilter }}</span> -->
              </template>
            </el-table-column>
            <el-table-column align="left" label="纳税人名称" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.taxpayerName" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="我方抬头">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.ourTitle" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="申请人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column :sortable="curTabName === 'all'?'custom':null" align="right" label="含税金额(元)" min-width="130" prop="amount">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.amountFen" :price="scope.row.amountFen / 100" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="开票项目">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.project" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="开票审批" min-width="140">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.approvalNo" :open-delay="800">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.approvalNo }}</div>
                  <div class="ellipsisOne" style="color: #406eff; cursor: pointer;" @click="goIssueInvoiceDetail(scope.row)">
                    {{ scope.row.approvalNo }}
                  </div>
                </el-tooltip>
                <div v-else >--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="开票人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.issuer" :label="scope.row.issuer" :user-id="scope.row.issuerId" />
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column :sortable="curTabName === 'all'?'custom':null" align="left" label="开票日期" min-width="150" prop="invoiceDate">
              <template slot-scope="scope">
                <span v-if="scope.row.invoiceDate">{{ scope.row.invoiceDate | format('YYYY/MM/DD HH:mm') }}</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          <empty-placeholder v-else style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="(curTabName === 'all' && list.total > 0) || (curTabName === 'selected' && selectedData.length > 0)"
            :current-page="curTabName === 'all'?list.page:selectedPage"
            :page-size="curTabName === 'all'?list.perPage:selectedPerPage"
            :total="curTabName === 'all'?list.total:selectedData.length"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage?'total, prev, next,jumper':'total, prev, pager, next, sizes,jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="multiple && !hasSeleted" size="small" type="primary" class="related-btn" @click="confirmRelatedContract">关联发票</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-if="!showMobilePage"
            v-show="(curTabName === 'all' && list.total > 0) || (curTabName === 'selected' && selectedData.length > 0)"
            :current-page="curTabName === 'all'?list.page:selectedPage"
            :page-size="curTabName === 'all'?list.perPage:selectedPerPage"
            :total="curTabName === 'all'?list.total:selectedData.length"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getDepartmentAll } from '@/api/config';
import { getInvoiceList, getInvoiceTypes, getInvoiceProjectList, getOurTitleList } from '@/api/invoice';
import tableSelections from '@/mixins/tableSelections';
import { format } from '@/filters/date';
import TableAdaptive from '@/mixins/tableAdaptive';
import options from '@/views/legal/module/options';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import FilterInput from '@/components/Tool/filter';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { mapState } from 'vuex';

export default {
  name: 'RelatedContract',
  filters: {
    format,
    invoiceTypeFilter(num) {
      if (!num) return '--';
      // 开票类型（1: 增值税普通发票；2: 增值税专用发票 ；3: 国税通用机打发票； 4: 地税通用机打发票；5:收据）
      const obj = {
        '1': '增值税普通发票',
        '2': '增值税专用发票 ',
        '3': '国税通用机打发票',
        '4': '地税通用机打发票',
        '5': '收据'
      };
      return obj[num.toString()] || '--';
    }
  },
  components: {
    FilterInput,
    EmptyPlaceholder
  },
  mixins: [tableSelections, TableAdaptive],
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    excludeCancel: {
      type: Boolean,
      default: false
    },
    hasContractCode: {
      type: Boolean,
      default: false
    },
    confirmText: {
      type: String,
      default: '关联发票'
    },
    isAbandon: { // 是否来源发票作废
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterInput: {},
      page: 1,
      perPage: 20,
      drawerShow: false,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      selectedPage: 1,
      selectedPerPage: 20,
      sortType: '',
      sortName: '',
      listLoading: false,
      options,
      idKey: 'id', // 多选框参数
      tableRefName: 'legalTableRef',
      curTabName: 'all',
      selectedData: [],
      invoiceTypes: [],
      invoiceProjectList: [],
      deptTreeList: [],
      ourTitleList: [],
      invoiceStatus: [
        { value: 0, label: '执行中' },
        { value: 1, label: '已完成' },
        { value: 2, label: '作废中' },
        { value: 3, label: '已作废' }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasSeleted() {
      return this.multipleSelectionAll.length > 0;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 280 : 223;
    },
    filterList() {
      return [
        // 输入框
        { keyword: 'number', name: '发票号码', inputType: 'number', labelWidth: '70px', type: 'input' },
        { keyword: 'taxpayerName', name: '纳税人名称', labelWidth: '100px', type: 'input' },
        { keyword: 'proposer', name: '申请人', labelWidth: '70px', type: 'input' },
        { keyword: 'amount', name: '含税金额', labelWidth: '100px', type: 'inputRange' },
        { keyword: 'approvalNo', name: '开票审批', labelWidth: '70px', type: 'input' },
        { keyword: 'issuer', name: '开票人', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'invoiceType', name: '发票类型', valueName: 'label', type: 'select', options: this.invoiceTypes },
        { keyword: 'project', name: '开票项目', valueName: 'label', type: 'select', options: this.invoiceProjectList },
        { keyword: 'ourTitle', name: '我方抬头', valueName: 'label', type: 'select', options: this.ourTitleList },
        { keyword: 'invoiceStatus', name: '状态', type: 'select', options: this.invoiceStatus },
        // { keyword: 'applyDepartment', name: '申请部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        // { keyword: 'department', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        // 日期
        { keyword: 'invoiceDate', name: '开票日期', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    rangeKeyArr() {
      return [
        { attr: 'invoiceDate', start: 'invoiceDateStart', end: 'invoiceDateTimeEnd', type: 'time' },
        { attr: 'amount', start: 'amountStart', end: 'amountEnd', type: 'number' }
      ];
    },
    arrayKeyArr() {
      return ['applyDepartment', 'department'];
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow && this.curTabName === 'all') this.setSelectRow(data.items);
        });
      },
      deep: true
    }
  },
  methods: {
    // 初始获取数据
    openDialog(data) {
      this.queryInvoiceTypes();
      this.queryInvoiceProjectList();
      // this.queryDeptTreeList();
      this.queryOurTitleList();

      this.fetchData();
      this.curTabName = 'all';
      this.selectedData = data;
      this.multipleSelectionAll = data;
      this.drawerShow = true;
    },
    closeDialog() {
      this.drawerShow = false;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      if (this.curTabName === 'all') {
        this.fetchData();
      }
    },
    // fitter
    queryClick() {
      this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.filterInput = {};
      this.queryClick();
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.list.perPage = val;
        this.fetchData(true);
      } else {
        this.selectedPerPage = val;
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.list.page = toPage;
        this.fetchData();
      } else {
        this.selectedPage = toPage;
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    // 获取列表数据
    fetchData(reset = false) {
      try {
        if (reset) this.list.page = 1;
        this.listLoading = true;
        const params = _.cloneDeep(this.filterInput);
        paramsRangeFormat(this.rangeKeyArr, params);
        paramsAryToStr(this.arrayKeyArr, params);
        params.sortName = this.sortName || '';
        params.sortType = this.sortType || '';
        params.page = this.list.page;
        params.perPage = this.list.perPage;
        if (this.isAbandon) params.status = 1; // 只筛选已完成发票
        getInvoiceList(params).then(({ data }) => {
          this.list = data;
          this.listLoading = false;
        }, result => {
          this.listLoading = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 关联发票
    confirmRelatedContract() {
      this.$emit('confirmRelatedContract', this.selectedData);
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else {
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;
      if (this.setSelectRow && this.curTabName === 'selected') this.setSelectRow(this.selectedTableData);
    },
    // 跳转发票详情
    goInvoice(row) {
      // if ((row.status === 2 || row.status === 3) && row.abandonId && row.abandonProcessId) {
      //   // 作废中、已作废，新窗口打开作废审批详情
      //   this.goInvoiceAbandon(row);
      //   return;
      // }
      const routeUrl = this.$router.resolve({
        name: 'invoiceDetail',
        params: { id: row.id }
      });
      window.open(routeUrl.href, '_blank');
    },
    goInvoiceAbandon(item) {
      const routeUrl = this.$router.resolve({
        name: 'invoiceAbandonDetail',
        query: { id: item.abandonId, processId: item.abandonProcessId }
      });
      window.open(routeUrl.href, '_blank');
    },
    onBackClick() {
      this.$refs.drawerBox.closeDrawer();
    },
    goIssueInvoiceDetail(rowData) {
      const { applyId, processId } = rowData;
      if (applyId && processId) {
        const url = this.$router.resolve({
          name: 'issueInvoiceDetail',
          query: {
            issueId: applyId,
            processId: processId
          }
        });
        window.open(url.href, '_blank');
      }
    },
    // 部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    // 发票类型
    queryInvoiceTypes() {
      getInvoiceTypes({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '发票类型'
            });
          });
          this.invoiceTypes = result;
        }
      });
    },
    // 开票项目
    queryInvoiceProjectList() {
      getInvoiceProjectList({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '开票项目'
            });
          });
          this.invoiceProjectList = result;
        }
      });
    },
    // 我方抬头
    queryOurTitleList() {
      getOurTitleList({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '我方抬头'
            });
          });
          this.ourTitleList = result;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.link {
  color: #406eff;
  cursor: pointer;
}
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    &::v-deep {
      .pagination-flex {
        position: absolute;
        width: 100% !important;
      }
      .el-table__header th {
        height: 49px !important;
      }
    }
  }
  .tab-content {
    margin: 17px 0 8px;
    &::v-deep {
      .el-tabs__header  {
        margin-bottom: 0 !important;
        border-bottom: 1px solid #ddd;
        .el-tabs__nav {
          border: none !important;
        }
        .el-tabs__item {
          padding: 0 12px !important;
          height: 32px !important;
          line-height: 32px !important;
          margin-right: 8px;
          border: 1px solid #ddd;
          border-radius: 4px 4px 0px 0px;
          color: #333;
          background: #f7f8fa;
          font-size: 16px;
          &:last-child {
            margin-right: 0px;
          }
          &.is-active {
            border-bottom-color: #FFFFFF !important;
            font-weight: bold;
            background: #fff;
            color: #406eff;
          }
        }
      }
      .el-badge__content{
        background: #FB5227;
        transform: translateY(5px);
      }
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
</style>
